package com.sykj.seaflow.warm.core.convert2;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sykj.seaflow.warm.core.listener.GlobalAssignmentListener;
import com.sykj.seaflow.warm.core.listener.GlobalCreateListener;
import com.sykj.seaflow.warm.module.def.bean.SeaFlowNode;
import org.dromara.warm.flow.core.entity.Node;
import org.dromara.warm.flow.core.enums.NodeType;
import org.dromara.warm.flow.core.enums.SkipType;
import org.dromara.warm.flow.core.listener.Listener;
import org.dromara.warm.flow.orm.entity.FlowSkip;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

public abstract  class NodeConvertAbstract implements NodeConvert {


    public SeaFlowNode getNode(JSONObject jsonObject) {
        SeaFlowNode node1 = new SeaFlowNode();
        // 节点类别
        String nodeType = jsonObject.getStr("nodeType");
        // nodeId 作为code
        String nodeCode = jsonObject.getStr("nodeId");
        String nodeName = jsonObject.getStr("nodeName");

        //权限相关 额外配置项
        JSONObject config = jsonObject.getJSONObject("properties");
        if(ObjectUtil.isNotEmpty(config)){
            String permission = convertPermissionMap(config);
            node1.setPermissionFlag(permission);
            BigDecimal nodeRatio = config.getBigDecimal("nodeRatio");
            // 多个用逗号分割， 这里先写死
            node1.setListenerType(String.join(",", Listener.LISTENER_ASSIGNMENT, Listener.LISTENER_CREATE));
            node1.setListenerPath(String.join("@@", GlobalAssignmentListener.class.getName(),
                    GlobalCreateListener.class.getName()));
            // 审批为空配置信息,  在 GlobalCreateListener中判断为空处理
            String emptyApprove = config.getStr("emptyApprove");
            node1.setEmptyApprove(emptyApprove);
            // 按钮配置
            node1.setButtonJson(config.getStr("buttons"));
        }

        node1.setNodeType(NodeType.getKeyByValue(nodeType));
        node1.setNodeCode(nodeCode);
        node1.setNodeName(nodeName);
        return node1;
    }

    public SeaFlowNode getEmptyNode(String nodeId, String nextNodeId){
        // 并行网关（出） 后面再加一个空节点
        SeaFlowNode emptyNode = new SeaFlowNode();
        emptyNode.setNodeName("自动通过");
        emptyNode.setNodeCode(nodeId);
        emptyNode.setNodeType(NodeType.BETWEEN.getKey());
        // 设置空类别自动通过， 区分前端审批人为空的配置
        String emptyApprove = "{\"type\":\"EMPTY\",\"value\":[]}";
        emptyNode.setEmptyApprove(emptyApprove);
        // 多个用逗号分割， 这里先写死
        emptyNode.setListenerType(String.join(",", Listener.LISTENER_ASSIGNMENT, Listener.LISTENER_CREATE));
        emptyNode.setListenerPath(String.join("@@", GlobalAssignmentListener.class.getName(),
                GlobalCreateListener.class.getName()));

        FlowSkip emptySkip = new FlowSkip();
        emptySkip.setSkipType(SkipType.PASS.getKey());
        emptySkip.setNextNodeCode(nextNodeId);
        emptyNode.getSkipList().add(emptySkip);
        return emptyNode;
    }


     public List<Node> nextNode(SeaFlowNode pNode, JSONObject childNode, String startNodeId, String endNodeId,String lastLineNodeId){
         return NodeConvertHandler.convert(pNode,childNode, startNodeId, endNodeId, lastLineNodeId);
    }

    private static String convertPermissionMap(JSONObject config) {
        String roleCode= "role";
        String userCode= "user";
        String deptCode = "dept";
        StringBuilder permission = new StringBuilder();
        // 设置权限  role, user 等
        JSONArray permissions = config.getJSONArray("permissions");
        // 权限组合
        JSONObject combination = config.getJSONObject("combination");
        if(ObjectUtil.isNull(permissions)){
            return null;
        }
        List<String> list = permissions.stream().map(String::valueOf).collect(Collectors.toList());//.toList();
        if(ObjectUtil.isEmpty(list)){
            return null;
        }
        if(list.contains(roleCode)){
            JSONArray jsonArray = combination.getJSONArray(roleCode);
            List<String> roleIds = jsonArray.stream().map(r -> ((JSONObject) r).getStr("id")).collect(Collectors.toList());//.toList();
            if(ObjectUtil.isNotEmpty(roleIds)){
                for(String roleId : roleIds){
                    permission.append("role:").append(roleId).append(",");
                }
//                String collect = roleIds.stream().collect(Collectors.joining(","));
//                permission += "role:" + collect + "@@";
            }
        }

        if(list.contains(userCode)){
            JSONArray jsonArray = combination.getJSONArray(userCode);
            List<String> userIds = jsonArray.stream().map(r -> ((JSONObject) r).getStr("id")).collect(Collectors.toList());// .toList();
            if(ObjectUtil.isNotEmpty(userIds)){
                for(String userId : userIds){
                    permission.append("user:").append(userId).append(",");
                }
            }
        }

        if(list.contains(deptCode)){
            JSONArray jsonArray = combination.getJSONArray(deptCode);
            List<String> deptIds = jsonArray.stream().map(r -> ((JSONObject) r).getStr("id")).collect(Collectors.toList());// .toList();
            if(ObjectUtil.isNotEmpty(deptIds)){
                for(String userId : deptIds){
                    permission.append("dept:").append(userId).append(",");
                }
            }
        }
        if(permission.length() > 0) {
            permission = new StringBuilder(permission.substring(0, permission.length() - 1));
        }
        return permission.toString();
    }


    public static void main(String[] args) {
        String json = "{        \"permissions\": [\n" +
                "                \"user\",\n" +
                "                \"role\"\n" +
                "            ],\n" +
                "            \"combination\": {\n" +
                "                \"role\": [\n" +
                "                    {\n" +
                "                        \"id\": \"1813509485149945858\",\n" +
                "                        \"roleName\": \"空角色\"\n" +
                "                    },\n" +
                "                    {\n" +
                "                        \"id\": \"1813120366464937986\",\n" +
                "                        \"roleName\": \"普通人员\"\n" +
                "                    },\n" +
                "                    {\n" +
                "                        \"id\": \"1812054642967375874\",\n" +
                "                        \"roleName\": \"超级管理员\"\n" +
                "                    }\n" +
                "                ],\n" +
                "                \"user\": [\n" +
                "                    {\n" +
                "                        \"id\": \"1\",\n" +
                "                        \"name\": \"超管\"\n" +
                "                    }\n" +
                "                ]\n" +
                "            }}";

        JSONObject entries = JSONUtil.parseObj(json);
        String s = convertPermissionMap(entries);
        System.out.printf(s);

    }
}
